﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestThread
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            InitialProcessBar();
        }

        private void InitialProcessBar()
        {
            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;
            progressBar1.Value = 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string source = textBox1.Text.Trim();
            string target = textBox2.Text.Trim();
            BigFileCopy(source, target);
        }

        private void BigFileCopy(string source, string target)
        {
            using (FileStream fsReader = new FileStream(source,FileMode.Open,FileAccess.Read))
            {
                using (FileStream fsWrite = new FileStream(target,FileMode.Create,FileAccess.Write))
                {
                    byte[] array = new byte[512 * 512];
                    int count = fsReader.Read(array, 0, array.Length);
                    while (count > 0)
                    {
                        fsWrite.Write(array, 0, count);
                        int value = (int)((fsWrite.Position * 1.0) / (fsReader.Length) * 100);
                        count = fsReader.Read(array, 0, array.Length);
                        progressBar1.Invoke(new Action<int>(
                            u => progressBar1.Value = u
                            ), value);
                    }
                    MessageBox.Show("文件拷贝完成！","",MessageBoxButtons.OK);
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(() =>
            {
                string source = textBox1.Text.Trim();
                string target = textBox2.Text.Trim();
                BigFileCopy(source, target);
            }));
            thread.Start();
        }
    }
}
